package com.vf.admin.utils.httpqingqiu;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tencentyun.TLSSigAPIv2;
import com.vf.admin.utils.WYIM.dto.TxImZaiXian;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 网络请求
 */
public class HttpPostUtils {
    public static HttpPostUtils getInstance(){
        return new HttpPostUtils();
    }

    private HttpPostUtils(){
    }

    public String sendPost(String url, String param)
            throws UnsupportedEncodingException {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            //
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));// 设置编码,否则中文乱码

            String line;
            while ((line = in.readLine()) != null) {
                result += "" + line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        result = new String(result.getBytes("ISO-8859-1"), "GBK");
        return result;
    }

    public String sendPostBody(String httpurl, String param,String bodyStr) {
        try{
            URL url = new URL(httpurl);
            // 打开和URL之间的连接
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("POST");//请求post方式
            con.setUseCaches(false); // Post请求不能使用缓存
            con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false

            //设置header内的参数 connection.setRequestProperty("健, "值");
//            con.setRequestProperty("Content-Type", "application/json");
//            con.setRequestProperty("isTree", "true");
//            con.setRequestProperty("isLastPage", "true");

            //设置body内的参数，put到JSONObject中

            // 建立实际的连接
            con.connect();

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
            writer.write(bodyStr);
            writer.flush();

            // 获取服务端响应，通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();

            // 关闭连接
            con.disconnect();

            // 打印读到的响应结果
            //.getBytes("ISO-8859-1"), "GBK"    会出现文字变成？的情况
            return new String(sbf.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) throws Exception{
        //腾讯云IM签名创建 所有IM服务端接口都需要签名信息
        TLSSigAPIv2 ssigApi = new TLSSigAPIv2(1400800054,"da952eadd25735813888e18bf44ba090993cc482a24cd6787445002ea6bd060a");
        String sigStr = ssigApi.genSig("123",604800); //有效期7天：7*24*60*60秒
        System.out.println(sigStr);

        //用户腾讯IM用户在线状态
        String url = "https://console.tim.qq.com/v4/openim/querystate?sdkappid=1400800054&identifier=123&usersig="+sigStr+"&random=99999999&contenttype=json";
        //封装参数
        TxImZaiXian zaiXian = new TxImZaiXian();
        zaiXian.setIsNeedDetail(1);
        List<String> userIdS = new ArrayList<String>();
        userIdS.add("123");
        zaiXian.setTo_Account(userIdS);
        String jsonConent = JSON.toJSONString(zaiXian);
        System.out.println("jsonConent:"+jsonConent);

        //发送请求
        String resultContent = HttpPostUtils.getInstance().sendPostBody(url,"",jsonConent);
        System.out.println(resultContent);
    }

    public  String sendGet(String url, String param) throws UnsupportedEncodingException {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent","(Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36");

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                //System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        result = new String(result.getBytes("ISO-8859-1"), "GBK");

        return result;
    }

    public String sendGets(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                //System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }



}
